package com.my.Config;


import com.my.userservlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import java.util.ArrayList;


@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{


  @Override
  protected void configure(HttpSecurity http) throws Exception {

    CharacterEncodingFilter filter = new CharacterEncodingFilter();
    filter.setEncoding("UTF-8");
    filter.setForceEncoding(true);
    //处理乱码问题
    http.addFilterBefore(filter,CsrfFilter.class);

//    拦截配置 ,,,,
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http.authorizeRequests();

    // /resources signup about 任何人都可以访问
    authorizeRequests.antMatchers("/resources/**", "/signup", "/about","/admin/**").permitAll();
    // /admin 需要ADMIN权限才能访问

    authorizeRequests.antMatchers("/admin/**").hasRole("USER");
      //    撞车的url以后配的为准
    authorizeRequests.antMatchers("/admin/**").hasRole("ADMIN");
// /db 需要 ADMIN和dba权限才能访问
    authorizeRequests.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')");

    //所有的页面需要登录才能访问
    authorizeRequests.anyRequest().authenticated();


    FormLoginConfigurer<HttpSecurity> formLogin = http.formLogin();
    //为认证转发的登录页
    formLogin.loginPage("/login").permitAll();
    //登录成功转发的url
    formLogin.successForwardUrl("/success").permitAll();
    //失败转发的url
    formLogin.failureForwardUrl("/loginError").permitAll();

    //登出配置 无效的原因是moren启用了csrf保护,只处理post表单请求
    LogoutConfigurer<HttpSecurity> logout = http.logout();
    //注销的url
    logout.logoutUrl("/logout");
    //注销成功转发url
    logout.logoutSuccessUrl("/outsuccess").permitAll();


  }


  @Bean
  //用来登录查询数据密码的bean
  protected UserDetailsService userDetailsService() {
    UserDetailsService userDetailsService = new UserDetailsService() {
      @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ArrayList<GrantedAuthority> arrayList = null;
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        // spring 5.x必须使用密文匹配,不然不通过
        String pwd=bCryptPasswordEncoder.encode("123456");
//        String pwd = "123456";
        System.out.println(username);
        if (username.equals("123")) {
          arrayList = new ArrayList<>();
          //授权必须加前缀ROLE_
          arrayList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        } else if (username.equals("李四")) {
          arrayList = new ArrayList<>();
          arrayList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
          arrayList.add(new SimpleGrantedAuthority("ROLE_DBA"));
        }
        return new User(username, pwd, arrayList);
      }
    };
    return userDetailsService;
  }

  //  // @formatter:off
//  @Bean
//  public UserDetailsService myuserDetailsService()  {
//    UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("ADMIN").build();
//
//    return new InMemoryUserDetailsManager(user);
//  }


  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {

   //让UserDetailsService能够生效
    auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());

  }
}
